import React, { useState } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { useAppDispatch } from "../../app/hooks";
import { editAddressList } from "../../app/modules/address/addressSlice";

const Index = () => {

  const dispatch = useAppDispatch();
	const navigate = useNavigate()
	const location = useLocation()
	const item = location.state as any
	const [nickname, setNickname] = useState(item.nickname);
  const [tel, setTel] = useState(item.tel);
  const [address, setAddress] = useState(item.address);
	
  const handleEditaddress = () => {
    const data = {
      nickname,
      tel,
      address,
			id: item.id
    };

    if (data.address.trim() === "") {
      return alert("地址不可以为空！！");
    }

    if (!/^1[3-9]\d{9}$/.test(data.tel)) {
      return alert("手机号格式不正确");
    }

    dispatch(editAddressList(data)).then(() => {
			navigate(-1)
		})
  };
  return (
    <div className="add">
      <div>
        <span>昵称：</span>
        <input
          type="text"
          value={nickname}
          onChange={(e) => setNickname(e.target.value)}
        />
      </div>
      <div>
        <span>电话：</span>
        <input
          type="text"
          value={tel}
          onChange={(e) => setTel(e.target.value)}
        />
      </div>
      <div>
        <span>地址：</span>
        <input
          type="text"
          value={address}
          onChange={(e) => setAddress(e.target.value)}
        />
      </div>
      <button onClick={handleEditaddress}>编辑</button>
    </div>
  );
};

export default Index;
